const express = require('express');
let router = express.Router();

//日志
const {
    logger
} = require('../../config/logger');

const Response = require('../../utils/response')

//引入数据库连接池
const pool = require('../../config/mysql');
//引入数据库语句
const query = require('../../db/leaseQuery/leaseQuery');

//解析token
const {
    token_sign,
    token_verify
} = require('../../config/jwt')

//引入时间模块
const sd = require('silly-datetime');

//解析from
const multiparty = require('multiparty')
//存储文件 
const path = require('path');
const fs = require('fs');


//获取栋数信息
router.get('/buildings', function (req, res) {
    pool.query(query.select_buildings, (error, result) => {
        if (error) {
            res.json(Response.error("获取栋数信息失败", null));
            logger().error("获取栋数信息失败: " + error);
        } else {
            const data = JSON.parse(JSON.stringify(result));
            res.json(Response.success("获取栋数信息成功", data));
        }
    });
})

//根据栋数获取住户信息
router.get('/house', function (req, res) {
    const buildingId = req.query.buildingId;
    pool.query(query.select_house, buildingId, (error, result) => {
        if (error) {
            res.json(Response.error("获取该栋住房信息失败", null));
            logger().error("获取该栋住房信息失败: " + error);
        } else {
            const data = JSON.parse(JSON.stringify(result));
            res.json(Response.success("获取该栋住房信息成功", data));
        }
    });
})

//获取租赁列表
router.get('/leaseList', function (req, res) {
    const count = req.query.count ? parseInt(req.query.count) : 10;
    const page = req.query.page ? parseInt((req.query.page)) - 1 : 0;
    pool.query(query.select_lease, [count, page], (error, result) => {
        if (error) {
            res.json(Response.error("获取租赁列表失败", null));
            logger().error("获取租赁列表失败: " + error);
        } else {
            const data = JSON.parse(JSON.stringify(result));
            res.json(Response.success("获取租赁列表成功", data));
        }
    });
})

//获取租赁列表(价格区间筛选)
router.get('/leaseList_BetweenPrice', function (req, res) {
    const count = req.query.count ? parseInt(req.query.count) : 10;
    const page = req.query.page ? parseInt((req.query.page)) - 1 : 0;
    const min = parseInt((req.query.min));
    const max = parseInt((req.query.max));
    pool.query(query.select_lease_between, [min, max, count, page], (error, result) => {
        if (error) {
            res.json(Response.error("获取租赁列表(价格区间筛选)失败", null));
            logger().error("获取租赁列表(价格区间筛选)失败: " + error);
        } else {
            const data = JSON.parse(JSON.stringify(result));
            res.json(Response.success("获取租赁列表(价格区间筛选)成功", data));
        }
    });
})

//获取聊天记录
router.get('/chatRecord', function (req, res) {
    const token = req.headers.authorization;
    const sender = req.query.sender;
    const receiver = req.query.receiver;
    const {
        userId
    } = token_verify(token);

    pool.query(query.select_chat_all, [sender, receiver], (error, result) => {
        if (error) {
            res.json(Response.error("获取聊天失败", null));
            logger().error("获取聊天失败: " + error);
        } else {
            const data = JSON.parse(JSON.stringify(result));
            if (userId == receiver) {
                //将信息置为已读状态
                pool.query(query.change_chat_status, [sender, receiver], (error, result) => {
                    if (error) {
                        res.json(Response.error("修改消息状态失败", null));
                        logger().error("获取聊天失败: " + error);
                        return;
                    }
                });
            }
            res.json(Response.success("获取聊天成功", data));
        }
    });
})

//业主获取我名下租赁的房子
router.get('/myLease', function (req, res) {
    const token = req.headers.authorization;
    const {
        userId
    } = token_verify(token);

    pool.query(query.select_my_house, userId, (error, result) => {
        if (error) {
            res.json(Response.error("获取名下的出租房子失败", null));
            logger().error("获取名下的出租房子失败: " + error);
        } else {
            const data = JSON.parse(JSON.stringify(result));
            res.json(Response.success("获取名下的出租房子成功", data));
        }
    });
})

//业主发布租赁信息
router.post('/publish', function (req, res) {
    const token = req.headers.authorization;
    const {
        role
    } = token_verify(token); //发布者ID
    if (role !== 1) {
        res.json(Response.error("请使用房东账户发布租赁信息", null));
        logger().error("下架租赁房源失败: 权限不足");
    }
    const ht = req.protocol; // 获取协议（http或者https）
    const host = req.headers.host; // 获取域名和端口号
    let form = new multiparty.Form({
        uploadDir: path.join(__dirname, '../../../public/images/lease')
    }) // 设置文件存储路径
    const time = sd.format(new Date(), 'YYYY-MM-DD HH:mm');
    form.parse(req, (err, msg, files) => {
        try {
            const houseId = msg['houseId'][0];
            const title = msg['title'][0];
            const price = msg['price'][0];
            const introduce = msg['introduce'][0];
            const contacts = msg['contacts'][0];
            const tel = msg['tel'][0];
            const keyword = msg['keyword'][0];
            const image = files['image'] //多图存储
            let urlList = [];
            for (let i = 0; i < image.length; i++) {
                const newPath = form.uploadDir + "/" + image[i].originalFilename
                fs.renameSync(image[i].path, newPath);
                const url = ht + "://" + host + "/images/lease/" + image[i].originalFilename;
                urlList.push(url);
            }
            const urls = urlList.join(",");
            pool.query(query.insert_lease, [houseId, title, price, urls, introduce, contacts, tel, keyword, time], (error, result) => {
                if (error) {
                    res.json(Response.error("发布租赁信息失败", null));
                    logger().error("发布租赁信息失败: " + error);
                } else {
                    res.json(Response.success("发布租赁信息成功", null));
                }
            });
        } catch (error) {
            res.json(Response.error("发布租赁信息失败", null));
            logger().error("发布租赁信息失败: " + error);
        }
    })
});

//业主修改租赁的信息
router.post('/changeInfo', function (req, res) {
    const token = req.headers.authorization;
    const {
        role
    } = token_verify(token); //发布者ID
    if (role !== 1) {
        res.json(Response.error("请使用房东账户发布租赁信息", null));
        logger().error("修改租赁的信息失败: 权限不足");
        return;
    }
    const ht = req.protocol; // 获取协议（http或者https）
    const host = req.headers.host; // 获取域名和端口号
    let form = new multiparty.Form({
        uploadDir: path.join(__dirname, '../../../public/images/lease')
    }) // 设置文件存储路径
    form.parse(req, (err, msg, files) => {
        try {
            const leaseId = msg['leaseId'][0];
            const title = msg['title'][0];
            const price = msg['price'][0];
            const introduce = msg['introduce'][0];
            const contacts = msg['contacts'][0];
            const tel = msg['tel'][0];
            const keyword = msg['keyword'][0];
            const image = files['image'] //多图存储
            let urlList = [];
            for (let i = 0; i < image.length; i++) {
                const newPath = form.uploadDir + "/" + image[i].originalFilename
                fs.renameSync(image[i].path, newPath);
                const url = ht + "://" + host + "/images/lease/" + image[i].originalFilename;
                urlList.push(url);
            }
            const urls = urlList.join(",");
            pool.query(query.update_lease, [title, price, urls, introduce, contacts, tel, keyword, leaseId], (error, result) => {
                if (error) {
                    res.json(Response.error("修改租赁的信息失败", null));
                    logger().error("修改租赁的信息失败: " + error);
                } else {
                    res.json(Response.success("修改租赁的信息成功", null));
                }
            });
        } catch (error) {
            res.json(Response.error("修改租赁的信息失败", null));
            logger().error("修改租赁的信息失败: " + error);
        }
    })
});

//业主下架租赁房源
router.post('/offShelf', function (req, res) {
    const token = req.headers.authorization;
    const {
        role
    } = token_verify(token);
    if (role !== 1) {
        res.json(Response.error("权限不足", null));
        logger().error("下架租赁房源失败: 权限不足");
    } else {
        const leaseId = req.body.leaseId;
        pool.query(query.offShelf, leaseId, (error, result) => {
            if (error) {
                res.json(Response.error("下架租赁房源失败", null));
                logger().error("下架租赁房源失败: " + error);
            } else {
                res.json(Response.success("下架租赁房源成功", null));
                return;
            }
        });
    }
})

//根据房屋ID获取房间门牌号
router.get('/housePlateById', function (req, res) {
    const houseId = req.query.houseId;
    console.log(houseId)
    pool.query(query.select_plate_houseId, houseId, (error, result) => {
        if (error) {
            res.json(Response.error("获取该ID所属房间门牌号失败", null));
            logger().error("获取该ID所属房间门牌号失败: " + error);
        } else {
            const data = JSON.parse(JSON.stringify(result));
            res.json(Response.success("获取该ID所属房间门牌号成功", data));
        }
    });
})


module.exports = router;